package com.wbs.common;

import com.wbs.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {

    // 拦截 url ,对其进行处理

    private static final String START_TIME="requestStartTime";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理之前
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        log.info("request start url:{},params:{}",url, JsonMapper.obj2String(parameterMap));
        // 请求开始的时候记录时间
        long start=System.currentTimeMillis();
        request.setAttribute(START_TIME,start);
        return true;  // 返回 true 代表处理之前所有的请求都是成功的
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 正常请求处理之后，但是异常请求不会调用
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        long start= (long) request.getAttribute(START_TIME);
        long end=System.currentTimeMillis();
        log.info("request finish url:{},params:{},cost:{}",url, JsonMapper.obj2String(parameterMap),end-start);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 正常请求、异常请求之后都调用
        String url = request.getRequestURL().toString();
        Map parameterMap = request.getParameterMap();
        long start= (long) request.getAttribute(START_TIME);
        long end=System.currentTimeMillis();
        log.info("request exception url:{},params:{},cost:{}",url, JsonMapper.obj2String(parameterMap),end-start);
    }
}
